<template>
  <div class="p-4.5 h-full flex flex-col service-def">
    <div class="flex flex-row items-center">
      <div class="font-semibold text-5.7 pb-4.5 text-color-header flex-1">服务定义</div>
      <div>
        <a-button type="primary" @click="handleUpdate">确定</a-button>
      </div>
    </div>
    <div class="flex-1 bg-white flex flex-row overflow-hidden">
      <div class="w-60 p-4.5">
        <div
          v-for="(el, i) in tabData"
          :key="el.title"
          class="px-3 py-2 bg-gray-100 rounded cursor-pointer hover:bg-blue-100 mb-2"
          :class="{ '!bg-color-active text-white': selectedIndex === i }"
          @click="selectedIndex = i"
        >
          {{ el.title }}
        </div>
      </div>
      <div class="flex-1 h-full border-solid border-0 border-l border-color-split p-4.5 overflow-auto">
        <template v-if="selectedIndex === 0">
          <div class="mb-3"> 手势服务范例 </div>
          <div class="mb-6">
            <img src="../../assets/example1.jpg" style="width: 500px" />
          </div>
          <a-form>
            <a-form-item class="!mb-3" v-bind="validateInfos.algorithmServerAddress">
              <a-input v-model:value="defData.algorithmServerAddress" addon-before="算法服务器地址" />
            </a-form-item>
          </a-form>
          <a-table
            class="mb-3"
            :columns="handColumns"
            :data-source="handData"
            bordered
            :pagination="false"
            :loading="tableLoading"
          >
            <template #bodyCell="{ column, record }">
              <a-select
                v-if="column.dataIndex === 'startChannel' || column.dataIndex === 'endChannel'"
                v-model:value="record[column.dataIndex]"
                @change="channelChange($event as number, column.dataIndex, record)"
              >
                <a-select-option :value="0">0</a-select-option>
                <a-select-option :value="1">1</a-select-option>
              </a-select>
            </template>
            <template #title> 服务时间队列定义 </template>
          </a-table>
        </template>
        <template v-else>
          <div class="mb-3"> 动态关键字定义 </div>
          <div class="mb-3">
            <a-tag v-for="el in dyWords" :key="el" color="blue" closable>{{ el }}</a-tag>
            <a-popover v-model:visible="addWordVisible" trigger="click" title="新增关键字" placement="right">
              <template #content>
                <div class="mb-2">
                  <a-input v-model:value="newWord" placeholder="请输入动态关键字" />
                </div>
                <div class="text-right">
                  <a-button size="small" type="primary" @click="handleAddWord">确定</a-button>
                </div>
              </template>
              <a-tag style="background: #fff; border-style: dashed" class="cursor-pointer" @click="addWord">
                <plus-outlined />
                新增关键字
              </a-tag>
            </a-popover>
          </div>
          <a-table
            class="mb-3"
            :columns="voiceColumns"
            :data-source="voiceData"
            bordered
            :pagination="false"
            :loading="tableLoading"
          >
            <template #bodyCell="{ column }">
              <div v-if="column.dataIndex === 'send'">
                <span class="text-red-500 mr-2 cursor-pointer">删除</span>
                <span class="text-color-active cursor-pointer">下发</span>
              </div>
            </template>
            <template #title> 动态关键字下发 </template>
          </a-table>
        </template>
        <a-form>
          <a-form-item name="fullScore" class="!mb-2" v-bind="validateInfos.fullScore">
            <a-input-number v-model:value="defData.fullScore" addon-before="满分分值" class="w-full" />
          </a-form-item>
          <a-form-item name="aiScoreProportion" class="!mb-2" v-bind="validateInfos.aiScoreProportion">
            <a-input-number v-model:value="defData.aiScoreProportion" addon-before="AI平分占比" class="w-full" />
          </a-form-item>
          <a-form-item name="aiInvalidScore" class="!mb-2" v-bind="validateInfos.aiInvalidScore">
            <a-input-number v-model:value="defData.aiInvalidScore" addon-before="AI无效评分默认值" class="w-full" />
          </a-form-item>
          <a-form-item name="proportionOfManualScoring" class="!mb-0" v-bind="validateInfos.proportionOfManualScoring">
            <a-input-number
              v-model:value="defData.proportionOfManualScoring"
              addon-before="人工评分占比"
              class="w-full"
            />
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { PlusOutlined } from "@ant-design/icons-vue";
import { onMounted, ref, watch, reactive, nextTick } from "vue";
import { Api, getDef, updateDef } from "/@/api/main/civilizedService";
import { DefinitionItem, DeviceItem } from "/@/api/main/civilizedService/models";
import { useCURD } from "/@/hooks/useCURD";
import { CAMERA_TYPE, HAND_DEF_TYPE, VOICE_DEF_TYPE, PICKUP_TYPE } from "/@/utils/business";
import { Form, message } from "ant-design-vue";
import type { Rule } from "ant-design-vue/es/form";
/**
 * common
 */
const tabData = ref([
  { title: "手势服务定义", type: HAND_DEF_TYPE },
  { title: "三声服务定义", type: VOICE_DEF_TYPE },
]);
const selectedIndex = ref(0);
const defData = ref<Partial<DefinitionItem>>({
  algorithmServerAddress: "0.0.0.0",
  fullScore: 0,
  aiScoreProportion: 0,
  aiInvalidScore: 0,
  proportionOfManualScoring: 0,
});
const { tableData, tableLoading, reloadTable, curd } = useCURD<DeviceItem>({
  updateUrl: Api.devicesPage,
  getPageUrl: Api.devicesPage,
  pageSize: 999,
  loadOnMounted: false,
});
function handleDefData(data) {
  ["fullScore", "aiScoreProportion", "aiInvalidScore", "proportionOfManualScoring"].forEach((key) => {
    if (!data[key]) {
      data[key] = 0;
    }
  });
}
function handleSelectedIndex(index) {
  const target = tabData.value[index];
  let ipRequired = target.type === HAND_DEF_TYPE;
  if (ipRequired) {
    if (!handDefData.value) {
      getDef(HAND_DEF_TYPE).then((data) => {
        if (data) {
          handleDefData(data);
          handDefData.value = data;
          defData.value = { ...data };
        }
      });
    } else {
      defData.value = { ...handDefData.value };
    }
    if (!handData.value) {
      reloadTable({ model: { deviceType: CAMERA_TYPE } }).then(() => {
        handData.value = tableData.value;
      });
    }
  } else {
    if (!voiceDefData.value) {
      getDef(VOICE_DEF_TYPE).then((data) => {
        if (data) {
          handleDefData(data);
          voiceDefData.value = data;
          defData.value = { ...data };
        }
      });
    } else {
      defData.value = { ...voiceDefData.value };
    }
    if (!voiceData.value) {
      reloadTable({ model: { deviceType: PICKUP_TYPE } }).then(() => {
        voiceData.value = tableData.value;
      });
    }
  }
  //三声服务定义下算法服务器地址不是必填
  const rules = defRules.algorithmServerAddress;
  if (rules) {
    rules.forEach((rule) => {
      rule.required = ipRequired;
    });
  }
  const validateInfo = validateInfos.algorithmServerAddress;
  if (validateInfo) {
    validateInfo.required = ipRequired;
  }
}
watch(selectedIndex, handleSelectedIndex);
onMounted(() => {
  handleSelectedIndex(selectedIndex.value);
});
//form
const defRules: Record<string, Rule[]> = {
  algorithmServerAddress: [
    {
      required: true,
      pattern: /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/,
      message: "请输入正确的IP地址",
    },
  ],
  fullScore: [
    {
      required: true,
      message: "请输入满分值",
    },
  ],
  aiScoreProportion: [
    {
      required: true,
      message: "请输入AI平分占比",
    },
  ],
  aiInvalidScore: [
    {
      required: true,
      message: "请输入AI无效评分默认值",
    },
  ],
  proportionOfManualScoring: [
    {
      required: true,
      message: "请输入人工评分占比",
    },
  ],
};
const { validate, validateInfos, resetFields } = Form.useForm(defData, reactive(defRules));
function handleUpdate() {
  validate().then(async (data) => {
    const target = tabData.value[selectedIndex.value];
    if (target.type === HAND_DEF_TYPE) {
      data.id = handDefData.value?.id;
    } else {
      data.id = voiceDefData.value?.id;
      data.dynamicKeyword = dyWords.value.join(";");
    }
    const re = await updateDef(data);
    if (re) {
      message.success("操作成功");
      //更新数据
      getDef(target.type).then((data) => {
        if (data) {
          handleDefData(data);
          if (target.type === HAND_DEF_TYPE) {
            handDefData.value = data;
          } else {
            voiceDefData.value = data;
          }
          defData.value = { ...data };
        }
      });
    }
  });
}
/**
 * hand
 */
const handDefData = ref<DefinitionItem>();
const handData = ref<DeviceItem[]>();
const handColumns = ref([
  // {
  //   title: "岗亭",
  //   dataIndex: "toll",
  // },
  {
    title: "设备",
    dataIndex: "videoCameraName",
  },
  {
    title: "设备地址",
    dataIndex: "videoCameraIp",
  },
  {
    title: "服务起始时间触发通道",
    dataIndex: "startChannel",
  },
  {
    title: "服务结束时间触发通道",
    dataIndex: "endChannel",
  },
]);
async function channelChange(value: number, key: string, record: DeviceItem) {
  if (curd.update) {
    const re = await curd.update({
      id: record.id,
      [key]: value,
    });
    if (re) {
      message.success("更新成功");
    }
  }
}
/**
 * voice
 */
const voiceDefData = ref<DefinitionItem>();
const voiceData = ref<DeviceItem[]>();
const dyWords = ref<string[]>([]);
watch(defData, (val) => {
  if (val.dynamicKeyword) {
    const arr = val.dynamicKeyword.split(";");
    dyWords.value = arr;
  } else {
    dyWords.value = [];
  }
  handleDefData(val);
});
const voiceColumns = ref([
  // {
  //   title: "岗亭",
  //   dataIndex: "toll",
  // },
  {
    title: "设备",
    dataIndex: "videoCameraName",
  },
  {
    title: "设备地址",
    dataIndex: "videoCameraIp",
  },
  // {
  //   title: "操作",
  //   dataIndex: "send",
  // },
]);
const addWordVisible = ref(false);
const newWord = ref("");
function addWord() {
  addWordVisible.value = true;
  newWord.value = "";
}
function handleAddWord() {
  if (!newWord.value) {
    return message.error("请输入动态关键字");
  }
  if (newWord.value.indexOf(";") !== -1) {
    return message.error("关键字中不能含';'");
  }
  if (dyWords.value.includes(newWord.value)) {
    return message.error("该关键字已存在，请修改");
  }
  dyWords.value.push(newWord.value);
  addWordVisible.value = false;
}
</script>
<style lang="less">
.service-def {
  .ant-input-group-addon {
    font-weight: bolder;
  }
}
</style>
